package com.baizhi.springbootshiro.utils;

import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * jedis Utils
 *
 * @author Administrator
 */
@Component
public class JedisUtils implements AutoCloseable {
    Logger log = LoggerFactory.getLogger(JedisUtils.class);
    @Resource
    private JedisPool jedisPool;
    private Jedis jedis;

    public String set(String k, String v) {
        jedis = jedisPool.getResource();
        try {
            String result = jedis.set(k, v);
            log.info("set Result:{}", result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public String setEx(String k, String v, int exp) {
        jedis = jedisPool.getResource();
        try {
            return jedis.setex(k, exp, v);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return "";
    }

    public String get(String k) {
        jedis = jedisPool.getResource();
        try {
            return jedis.get(k);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return "";
    }

    public Long hSet(String key, String hashK, String hashV) {
        try {
            jedis = jedisPool.getResource();
            HashMap<String, String> hashMap = Maps.newHashMap();
            hashMap.put(hashK, hashV);
            return jedis.hset(key, hashMap);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return -9L;
    }

    public String hGet(String key, String hashK) {
        try {
            jedis = jedisPool.getResource();
            return jedis.hget(key, hashK);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return "";
    }

    public Long delete(String k) {
        jedis = jedisPool.getResource();
        Long aLong = jedis.del(k);
        return aLong;
    }

    public Long hdel(String key, String k) {
        Long aLong = jedis.hdel(key, k);
        return aLong;
    }

    @Override
    public void close() {
        if (!ObjectUtils.isEmpty(jedis)) {
            jedis.close();
        }
    }


}
